<?php
/**
 *APINAME:
 *Developer:
 *Complete:
 */

namespace app\index\controller;


use app\index\common\BaseController;
use app\index\model\Record;
use think\Db;
use think\facade\Request;

class UserController extends BaseController
{
    /**
     * 返回已开始项目
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function startProject(){
        $currPage = Request::get('currPage');
        $result = Db::table('project')
            ->distinct(true)
            ->join('user','user.id =project.user_id')
            ->where('start_time','<',time())
            ->where('end_time','>',time())
            ->field(['project.id','img','name','user.userName'])
            ->field(["FROM_UNIXTIME(end_time,'%Y-%m-%d %H:%i:%s') as end_time"])
            ->paginate(5,false,['page' => $currPage]);
        return $this->returnJson(self::OK,'返回已开始项目成功',$result);
    }

    /**
     * 返回用户参加的项目
     * @param Record $record
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function takePartIn(Record $record){
        $userId = $this->getUserId();
        $currPage = Request::get('currPage');
        $opt = $record->where('user_id','=',$userId)->select();
        $optId = '';
        foreach ($opt as $key => $value){
            $optId .= $opt[$key]['option_id'] . ',';
        }
        $optId = rtrim($optId,',');
        $pro = $record->optionModel()->distinct(true)->field('project_id')->whereIn('id',$optId)->select();
        $proId = '';
        foreach ($pro as $key => $value){
            $proId .= $pro[$key]['project_id'] . ',';
        }
        $proId = rtrim($proId,',');
        $result = Db::table('project')
            ->distinct(true)
            ->join('user','user.id =project.user_id')
            ->whereIn('project.id',$proId)
            ->field(['project.id','img','name','user.userName'])
            ->field(["FROM_UNIXTIME(end_time,'%Y-%m-%d %H:%i:%s') as end_time"])
            ->paginate(5,false,['page' => $currPage]);
        return $this->returnJson(self::OK,'返回用户参加的投票项目',$result);
    }
}